package com.tenghui.assisting.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.tenghui.common.core.domain.AjaxResult;
import com.tenghui.common.core.domain.entity.SysUser;
import com.tenghui.common.utils.DateUtils;
import com.tenghui.common.utils.SecurityUtils;
import com.tenghui.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Random;

import com.tenghui.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.tenghui.assisting.domain.OrdersProducts;
import com.tenghui.assisting.mapper.OrdersMapper;
import com.tenghui.assisting.domain.Orders;
import com.tenghui.assisting.service.IOrdersService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.util.CollectionUtils;

import static com.tenghui.common.utils.SecurityUtils.getUserId;

/**
 * 订单Service业务层处理
 *
 * @author tenghui
 * @date 2025-11-02
 */
@Service
public class OrdersServiceImpl implements IOrdersService
{
    @Autowired
    private OrdersMapper  ordersMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private ISysUserService  sysUserService;

    /**
     * 查询订单
     *
     * @param ordersId 订单主键
     * @return 订单
     */
    @Override
    public Orders selectOrdersByOrdersId(String ordersId)
    {
        return ordersMapper.selectOrdersByOrdersId(ordersId);
    }

    /**
     * 查询订单列表
     *
     * @param orders 订单
     * @return 订单
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders)
    {
        Long userId = getUserId();
        if(!SecurityUtils.isAdmin(userId)){
            if(SecurityUtils.hasRole("farmers")){
                // hasRole 验证用户是否拥有某个角色
                // 如果当前是农户角色，可以看到 属于自己的订单列表
                orders.setProductsUserId(userId);
            }else{
                // 如果是普通用户，只能看到自己创建的订单数据
                orders.setUserId(userId);
            }
        }
        return ordersMapper.selectOrdersList(orders);
    }

    /**
     * 新增订单
     *
     * @param orders 订单
     * @return 结果
     */
    @Transactional
    @Override
    public String insertOrders(Orders orders)
    {
        System.out.println(orders);
        System.out.println(orders.getProductsUserId());
        // 获取当前操作的用户id
        Long loginUserId = getUserId();
        orders.setCreateTime(DateUtils.getNowDate());
        orders.setUserId(loginUserId);
        // 获取当前日期和事件
        LocalDateTime now = LocalDateTime.now();
        // 格式化输出
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formatDateTime = now.format(dtf);
        // 生成一个三位的随机数
        String random = String.format("%03d", new Random().nextInt(1000));
        // 将订单号所需的数据拼接起来 并 插入订单对象中(NO + 年月日时分秒 + 三位随机数 + 下单用户ID)
        String ordersId = "NO" + formatDateTime + random + loginUserId;
        orders.setOrdersId(ordersId);

        int rows = ordersMapper.insertOrders(orders);
        insertOrdersProducts(orders);
        return ordersId;
    }

    /**
     * 批量新增订单
     *
     * @param orderss 订单List
     * @return 结果
     */
    @Override
    public int batchInsertOrders(List<Orders> orderss)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(orderss)) {
            try {
                for (int i = 0; i < orderss.size(); i++) {
                    int row = ordersMapper.insertOrders(orderss.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i >0 && i%100 == 0) || i == orderss.size() - 1;
                    if (bool){
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            }catch (Exception e){
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            }finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改订单
     *
     * @param orders 订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateOrders(Orders orders)
    {
        ordersMapper.deleteOrdersProductsByOrdersId(orders.getOrdersId());
        insertOrdersProducts(orders);
        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除订单
     *
     * @param ordersIds 需要删除的订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrdersByOrdersIds(String[] ordersIds)
    {
        ordersMapper.deleteOrdersProductsByOrdersIds(ordersIds);
        return ordersMapper.deleteOrdersByOrdersIds(ordersIds);
    }

    /**
     * 删除订单信息
     *
     * @param ordersId 订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrdersByOrdersId(String ordersId)
    {
        ordersMapper.deleteOrdersProductsByOrdersId(ordersId);
        return ordersMapper.deleteOrdersByOrdersId(ordersId);
    }

    /**
     * 支付订单
     */
    @Override
    public int payment(String[] ordersIds) {
        // 拿到每一个订单
        for (String ordersId : ordersIds) {
            // 根据订单号查询订单信息
            Orders orders = selectOrdersByOrdersId(ordersId);

            // 拿到订单金额
            BigDecimal totalPrice = orders.getTotalPrice();
            // 拿到订单所属的农户id
            Long productsUserId = orders.getProductsUserId();
            // 给农户增加账户余额
            int res = sysUserService.updateUserBalance(productsUserId, "increase", totalPrice.doubleValue());
            if(res <= 0)    return 0; // 余额更新失败
        }
        return 1;
    }

    /**
     * 新增订单产品信息
     *
     * @param orders 订单对象
     */
    public void insertOrdersProducts(Orders orders)
    {
        List<OrdersProducts> ordersProductsList = orders.getOrdersProductsList();
        String ordersId = orders.getOrdersId();
        if (StringUtils.isNotNull(ordersProductsList))
        {
            List<OrdersProducts> list = new ArrayList<OrdersProducts>();
            for (OrdersProducts ordersProducts : ordersProductsList)
            {
                ordersProducts.setOrdersId(ordersId);
                list.add(ordersProducts);
            }
            if (list.size() > 0)
            {
                ordersMapper.batchOrdersProducts(list);
            }
        }
    }
}
